import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, Slider, ColorPicker, Switch, message } from 'antd';
import { SendOutlined, SettingOutlined } from '@ant-design/icons';
import './index.css';
import mockDanmakus from '../../mock/index.js'
import { useTranslation } from 'react-i18next'
// 弹幕数据类型
interface DanmakuItem {
  id: string;
  content: string;
  color: string;
  time: number;
  speed: number;
  top: number;
}
// 弹幕组件属性
interface DanmakuProps {
  containerRef?: React.RefObject<HTMLDivElement>;
  width?: number | string;
  height?: number | string;
}
const Danmaku: React.FC<DanmakuProps> = ({ containerRef, width = '100%', height = '100%' }) => {
  const { t } = useTranslation()
  // 弹幕列表
  const [danmakuList, setDanmakuList] = useState<DanmakuItem[]>([]);
  // 输入内容
  const [inputValue, setInputValue] = useState('');
  // 弹幕颜色
  const [color, setColor] = useState('#ffffff');
  // 弹幕速度 (值越小越慢)
  const [speed, setSpeed] = useState(1);
  // 弹幕密度
  const [density, setDensity] = useState(30);
  // 弹幕透明度
  const [opacity, setOpacity] = useState(0.8);
  // 是否显示设置面板
  const [showSettings, setShowSettings] = useState(false);
  // 是否启用弹幕
  const [enabled, setEnabled] = useState(true);
  // 弹幕容器引用
  const danmakuContainerRef = useRef<HTMLDivElement>(null);
  // 生成随机ID
  const generateId = () => {
    return Math.random().toString(36).substring(2, 9);
  };
  // 生成随机高度
  const generateRandomTop = () => {
    const container = containerRef?.current || danmakuContainerRef.current;
    if (!container) return 0;
    // 根据密度调整可用高度范围
    const availableHeight = container.clientHeight * (density / 100);
    return Math.floor(Math.random() * availableHeight);
  };
  // 发送弹幕
  const sendDanmaku = () => {
    if (!inputValue.trim()) {
      message.warning(t('please_enter_barrage'));
      return;
    }
    const newDanmaku: DanmakuItem = {
      id: generateId(),
      content: inputValue,
      color,
      time: Date.now(),
      speed: speed,
      top: generateRandomTop(),
    };
    setDanmakuList(prev => [...prev, newDanmaku]);
    setInputValue('');
    // 存储弹幕数据
    storeDanmaku(newDanmaku);
  };
  // 存储弹幕到本地存储
  const storeDanmaku = (danmaku: DanmakuItem) => {
    try {
      const storedDanmakus = localStorage.getItem('danmakus');
      const danmakus = storedDanmakus ? JSON.parse(storedDanmakus) : [];
      danmakus.push(danmaku);
      // 只保留最近100条弹幕
      if (danmakus.length > 500) {
        danmakus.shift();
      }
      localStorage.setItem('danmakus', JSON.stringify(danmakus));
    } catch (error) {
      console.error('存储弹幕失败:', error);
    }
  };
  // 加载历史弹幕
  useEffect(() => {
    try {
      // 先展示模拟数据，但减少同时显示的数量
      const initialMockDanmakus = mockDanmakus.map((d: any,) => ({
        id: generateId(),
        content: d.content,
        color: d.color,
        time: Date.now(),
        top: generateRandomTop(),
        speed: 1 + Math.random() * 2, // 随机速度
      }));
      // 分批添加弹幕，而不是一次性全部添加
      const batchSize = 5; // 每批添加的弹幕数量
      // 先添加第一批
      setDanmakuList(initialMockDanmakus.slice(0, batchSize));
      // 然后每隔一段时间添加后续批次
      let currentBatch = 1;
      const totalBatches = Math.ceil(initialMockDanmakus.length / batchSize);
      const batchInterval = setInterval(() => {
        if (currentBatch >= totalBatches) {
          clearInterval(batchInterval);
          return;
        }
        const start = currentBatch * batchSize;
        const end = Math.min(start + batchSize, initialMockDanmakus.length);
        const nextBatch = initialMockDanmakus.slice(start, end);
        setDanmakuList(prev => [...prev, ...nextBatch]);
        currentBatch++;
      }, 5000); // 每8秒添加一批新弹幕
      // 延迟加载真实的历史弹幕
      setTimeout(() => {
        const storedDanmakus = localStorage.getItem('danmakus');
        if (storedDanmakus) {
          const danmakus = JSON.parse(storedDanmakus);
          // 分批加载历史弹幕
          const historicalBatchSize = 2; // 每批加载的历史弹幕数量
          const processedDanmakus = danmakus.map((d: DanmakuItem) => ({
            ...d,
            id: generateId(),
            top: generateRandomTop(),
            time: Date.now(),
          }));
          // 先添加第一批历史弹幕
          setDanmakuList(prev => [...prev, ...processedDanmakus.slice(0, historicalBatchSize)]);
          // 然后每隔一段时间添加后续批次
          let currentHistoricalBatch = 1;
          const totalHistoricalBatches = Math.ceil(processedDanmakus.length / historicalBatchSize);
          const historicalBatchInterval = setInterval(() => {
            if (currentHistoricalBatch >= totalHistoricalBatches) {
              clearInterval(historicalBatchInterval);
              return;
            }
            const start = currentHistoricalBatch * historicalBatchSize;
            const end = Math.min(start + historicalBatchSize, processedDanmakus.length);
            const nextBatch = processedDanmakus.slice(start, end);
            setDanmakuList(prev => [...prev, ...nextBatch]);
            currentHistoricalBatch++;
          }, 5000); // 每5秒添加一批历史弹幕
        }
      }, 15000); // 15秒后开始加载历史弹幕
    } catch (error) {
      console.error('加载历史弹幕失败:', error);
    }
  }, []);
  // 清理已播放完的弹幕
  useEffect(() => {
    const timer = setInterval(() => {
      setDanmakuList(prev =>
        prev.filter(item => {
          const elapsedTime = (Date.now() - item.time) / 1000;
          // 根据速度计算弹幕是否已经播放完毕
          const container = containerRef?.current || danmakuContainerRef.current;
          if (!container) return false;
          const duration = (container.clientWidth + 200) / (item.speed * 50);
          return elapsedTime < duration;
        })
      );
    }, 1000);
    return () => clearInterval(timer);
  }, [containerRef]);
  // 键盘事件处理
  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      sendDanmaku();
    }
  };
  return (
    <div className="danmaku-wrapper" style={{ width, height }}>
      {/* 弹幕显示区域 */}
      <div
        ref={danmakuContainerRef}
        className="danmaku-container"
        style={{ opacity: enabled ? 1 : 0 }}
      >
        {enabled && danmakuList.map(item => (
          <div
            key={item.id}
            className="danmaku-item"
            style={{
              color: item.color,
              top: `${item.top}px`,
              opacity: opacity,
              animationDuration: `${25 / item.speed}s`,
            }}
          >
            {item.content}
          </div>
        ))}
      </div>
      {/* 弹幕控制区域 */}
      <div className="danmaku-control">
        <div className="danmaku-input-area">
          <Input
            value={inputValue}
            onChange={e => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder={t('send_barrage')}
            maxLength={50}
            suffix={
              <div className="danmaku-input-actions">
                <ColorPicker
                  value={color}
                  onChange={(_, hex) => setColor(hex)}
                  size="small"
                />
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={sendDanmaku}
                >
                  {t('send')}
                </Button>
                <Button
                  icon={<SettingOutlined />}
                  onClick={() => setShowSettings(!showSettings)}
                />
              </div>
            }
          />
        </div>
        {/* 设置面板 */}
        {showSettings && (
          <div className="danmaku-settings">
            <div className="setting-item">
              <span>{t('enable_barrage')}</span>
              <Switch checked={enabled} onChange={setEnabled} />
            </div>
            <div className="setting-item">
              <span>{t('barrage_speed')}</span>
              <Slider
                min={1}
                max={10}
                value={speed}
                onChange={setSpeed}
              />
            </div>
            <div className="setting-item">
              <span>{t('barrage_density')}</span>
              <Slider
                min={10}
                max={100}
                value={density}
                onChange={setDensity}
              />
            </div>
            <div className="setting-item">
              <span>{t('opacity')}</span>
              <Slider
                min={0.1}
                max={1}
                step={0.1}
                value={opacity}
                onChange={setOpacity}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Danmaku;